package GUI;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JDesktopPane;
import javax.swing.JButton;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

import java.awt.GridLayout;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import java.awt.FlowLayout;
import java.awt.Color;
import java.awt.Dimension;

import java.awt.Component;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.JLabel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.JTextArea;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.JScrollBar;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;


import BUS.QueryProccessor;
import BUS.Server;
import DAO.RecordDAO;
import DAO.TableDAO;
import DTO.ColInfoDTO;
import DTO.ConstraintDTO;
import DTO.RecordDTO;
import DTO.TableDTO;
import javax.swing.JPopupMenu;
import java.awt.event.InputMethodListener;
import java.awt.event.InputMethodEvent;
import java.awt.Toolkit;

public class MainScreen extends JFrame {
	private static final long serialVersionUID = 1L;
	public static String _DATABASE_PATH = "MyDatabase.dat";
	private boolean isShowIconDatabase = true;
	private JPanel contentPane;
	private final JPanel panel_3 = new JPanel();
	private final JDesktopPane desktopPane = new JDesktopPane();
	private JLabel lblIconDatabase;
	private JPanel panel_Query;
	private JButton btnExecute;
	private JButton btnUpdate;
	private JButton btnDelete;
	private JButton btnInsert;
	private JButton btnCreate;
	private JButton btnQuery;
	private JPanel Panel_Output;
	private JTextArea textAreaQuery;
	private JPanel panel_NewTable;
	private JTable tableNewTable;
	private JTabbedPane tabbedPane;
	private JButton btnCreateTable;

	// Lay thong tin bang moi thong qua bien nay
	private MyNewTableModel myNewTableModel;
	private DefaultMutableTreeNode treeNode;
	private MyTreeModel myTreeModel;
	private DefaultMutableTreeNode root;
	private JTable tableContent;
	private JTree treeTable;
	private int newRow;
	private int port=3200;
	private static Server server;
	
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainScreen frame = new MainScreen();
					server = new Server();
					server.AllowConnect();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public MainScreen() {
		super("Server");
		setIconImage(Toolkit.getDefaultToolkit().getImage(MainScreen.class.getResource("/resource/Places-server-database-icon.png")));
		myPreInit();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		try {
			for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (UnsupportedLookAndFeelException e) {
			// handle exception
		} catch (ClassNotFoundException e) {
			// handle exception
		} catch (InstantiationException e) {
			// handle exception
		} catch (IllegalAccessException e) {
			// handle exception
		}
		setBounds(100, 100, 800, 580);

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu mnNewMenu = new JMenu("File");
		menuBar.add(mnNewMenu);

		JMenuItem mntmOpen = new JMenuItem("Open");
		mnNewMenu.add(mntmOpen);

		JMenuItem mntmNewMenuItem = new JMenuItem("Exit");
		mnNewMenu.add(mntmNewMenuItem);

		JMenu mnEdit = new JMenu("Connection");
		menuBar.add(mnEdit);

		JMenuItem mntmConfigConnection = new JMenuItem("Config Connection");
		mntmConfigConnection.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				mntmConfigConnection_actionPerformed();
			}
		});
		mnEdit.add(mntmConfigConnection);

		JMenu mnHelp = new JMenu("Help");
		menuBar.add(mnHelp);

		JMenuItem mntmAbout = new JMenuItem("About");
		mnHelp.add(mntmAbout);
		contentPane = new JPanel();
		contentPane.setBackground(Color.WHITE);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);

		JPanel Panel_Left = new JPanel();
		Panel_Left.setBorder(new LineBorder(Color.LIGHT_GRAY, 1, true));
		Panel_Left.setBackground(Color.WHITE);
		Panel_Left.setForeground(Color.RED);
		// Panel_Left.setFocusTraversalPolicy(new FocusTraversalOnArray(new
		// Component[]{tree}));

		JPanel Panel_Top = new JPanel();
		Panel_Top.setBackground(Color.WHITE);
		Panel_Top.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));

		btnQuery = new JButton("Query");
		btnQuery.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				btnQuery_Click(arg0);
			}
		});
		btnQuery.setVerticalTextPosition(SwingConstants.BOTTOM);
		btnQuery.setHorizontalTextPosition(SwingConstants.CENTER);
		btnQuery.setAlignmentY(Component.BOTTOM_ALIGNMENT);
		btnQuery.setAlignmentX(Component.CENTER_ALIGNMENT);
		btnQuery.setIcon(new ImageIcon(MainScreen.class
				.getResource("/resource/icon_query.png")));
		Panel_Top.add(btnQuery);

		btnCreate = new JButton("Create");
		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
			}
		});
		btnCreate.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				btnCreate_Click(arg0);
			}
		});
		btnCreate.setIcon(new ImageIcon(MainScreen.class
				.getResource("/resource/icon_add.png")));
		btnCreate.setVerticalTextPosition(SwingConstants.BOTTOM);
		btnCreate.setHorizontalTextPosition(SwingConstants.CENTER);
		btnCreate.setAlignmentY(1.0f);
		btnCreate.setAlignmentX(0.5f);
		Panel_Top.add(btnCreate);

		btnInsert = new JButton("Insert");
		btnInsert.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				textAreaQuery.setText("insert into <TableName> value(<Value1>,<Value2>,....)");
				ShowQueryScreen(true);
			}
		});
		btnInsert.setIcon(new ImageIcon(MainScreen.class
				.getResource("/resource/icon_addrecord.png")));
		btnInsert.setVerticalTextPosition(SwingConstants.BOTTOM);
		btnInsert.setHorizontalTextPosition(SwingConstants.CENTER);
		btnInsert.setAlignmentY(1.0f);
		btnInsert.setAlignmentX(0.5f);
		Panel_Top.add(btnInsert);

		btnDelete = new JButton("Delete");
		btnDelete.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				textAreaQuery.setText("Delte from <TableName> where .....");
				ShowQueryScreen(true);
			}
		});
		btnDelete.setIcon(new ImageIcon(MainScreen.class
				.getResource("/resource/icon_delete.png")));
		btnDelete.setVerticalTextPosition(SwingConstants.BOTTOM);
		btnDelete.setHorizontalTextPosition(SwingConstants.CENTER);
		btnDelete.setAlignmentY(1.0f);
		btnDelete.setAlignmentX(0.5f);
		Panel_Top.add(btnDelete);

		btnUpdate = new JButton("Update");
		btnUpdate.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				textAreaQuery.setText("Update <TableName> where .... set ....");
				ShowQueryScreen(true);
			}
		});
		btnUpdate.setIcon(new ImageIcon(MainScreen.class
				.getResource("/resource/icon_upate.png")));
		btnUpdate.setVerticalTextPosition(SwingConstants.BOTTOM);
		btnUpdate.setHorizontalTextPosition(SwingConstants.CENTER);
		btnUpdate.setAlignmentY(1.0f);
		btnUpdate.setAlignmentX(0.5f);
		Panel_Top.add(btnUpdate);

		tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent arg0) {
				tabChanged(arg0);
			}
		});
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane
				.setHorizontalGroup(gl_contentPane
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								gl_contentPane
										.createSequentialGroup()
										.addGroup(
												gl_contentPane
														.createParallelGroup(
																Alignment.LEADING)
														.addGroup(
																gl_contentPane
																		.createSequentialGroup()
																		.addGap(7)
																		.addComponent(
																				Panel_Left,
																				GroupLayout.PREFERRED_SIZE,
																				145,
																				GroupLayout.PREFERRED_SIZE)
																		.addGap(10)
																		.addComponent(
																				tabbedPane,
																				GroupLayout.DEFAULT_SIZE,
																				602,
																				Short.MAX_VALUE))
														.addGroup(
																gl_contentPane
																		.createSequentialGroup()
																		.addContainerGap()
																		.addComponent(
																				Panel_Top,
																				GroupLayout.DEFAULT_SIZE,
																				754,
																				Short.MAX_VALUE)))
										.addContainerGap()));
		gl_contentPane
				.setVerticalGroup(gl_contentPane
						.createParallelGroup(Alignment.LEADING)
						.addGroup(
								gl_contentPane
										.createSequentialGroup()
										.addGap(3)
										.addComponent(Panel_Top,
												GroupLayout.PREFERRED_SIZE, 71,
												GroupLayout.PREFERRED_SIZE)
										.addGroup(
												gl_contentPane
														.createParallelGroup(
																Alignment.LEADING)
														.addGroup(
																gl_contentPane
																		.createSequentialGroup()
																		.addGap(8)
																		.addComponent(
																				Panel_Left,
																				GroupLayout.DEFAULT_SIZE,
																				372,
																				Short.MAX_VALUE))
														.addGroup(
																gl_contentPane
																		.createSequentialGroup()
																		.addPreferredGap(
																				ComponentPlacement.RELATED)
																		.addComponent(
																				tabbedPane,
																				GroupLayout.DEFAULT_SIZE,
																				374,
																				Short.MAX_VALUE)))
										.addContainerGap()));

		panel_Query = new JPanel();
		tabbedPane.addTab("Query", null, panel_Query, null);
		panel_Query.setBackground(Color.WHITE);
		panel_Query.setBorder(new LineBorder(Color.LIGHT_GRAY, 1, true));

		btnExecute = new JButton("Execute");
		btnExecute.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				excuteQuery();
			}
		});
		btnExecute.setVisible(false);
		btnExecute.setVerticalTextPosition(SwingConstants.BOTTOM);
		btnExecute.setHorizontalTextPosition(SwingConstants.CENTER);
		btnExecute.setIcon(new ImageIcon(MainScreen.class
				.getResource("/resource/icon_run.png")));

		Panel_Output = new JPanel();
		Panel_Output.setVisible(false);
		Panel_Output.setBackground(Color.WHITE);
		Panel_Output.setBorder(new LineBorder(Color.LIGHT_GRAY, 1, true));
		
		lblResult = new JLabel("Message:");

		JLabel lblNewLabel_1 = new JLabel("Output");

		lblIconDatabase = new JLabel("Database");
		lblIconDatabase.setVerticalTextPosition(SwingConstants.BOTTOM);
		lblIconDatabase.setHorizontalAlignment(SwingConstants.CENTER);
		lblIconDatabase.setHorizontalTextPosition(SwingConstants.CENTER);
		lblIconDatabase.setIcon(new ImageIcon(MainScreen.class
				.getResource("/resource/Database.png")));
		
		scrollPane_3 = new JScrollPane();
		scrollPane_3.setVisible(false);
		GroupLayout gl_panel_Query = new GroupLayout(panel_Query);
		gl_panel_Query.setHorizontalGroup(
			gl_panel_Query.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_Query.createSequentialGroup()
					.addGroup(gl_panel_Query.createParallelGroup(Alignment.TRAILING)
						.addComponent(Panel_Output, GroupLayout.DEFAULT_SIZE, 575, Short.MAX_VALUE)
						.addGroup(gl_panel_Query.createSequentialGroup()
							.addContainerGap()
							.addComponent(scrollPane_3, GroupLayout.DEFAULT_SIZE, 481, Short.MAX_VALUE)
							.addGap(18)
							.addComponent(btnExecute, GroupLayout.PREFERRED_SIZE, 76, GroupLayout.PREFERRED_SIZE))
						.addGroup(Alignment.LEADING, gl_panel_Query.createSequentialGroup()
							.addGap(154)
							.addComponent(lblIconDatabase)))
					.addContainerGap())
		);
		gl_panel_Query.setVerticalGroup(
			gl_panel_Query.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_Query.createSequentialGroup()
					.addGap(15)
					.addGroup(gl_panel_Query.createParallelGroup(Alignment.LEADING)
						.addComponent(btnExecute, GroupLayout.PREFERRED_SIZE, 89, GroupLayout.PREFERRED_SIZE)
						.addComponent(scrollPane_3, GroupLayout.PREFERRED_SIZE, 104, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(lblIconDatabase, GroupLayout.PREFERRED_SIZE, 148, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(Panel_Output, GroupLayout.DEFAULT_SIZE, 54, Short.MAX_VALUE)
					.addContainerGap())
		);
		
		scrollPane_OutputSelect = new JScrollPane();
		scrollPane_OutputSelect.setVisible(false);
		GroupLayout gl_Panel_Output = new GroupLayout(Panel_Output);
		gl_Panel_Output.setHorizontalGroup(
			gl_Panel_Output.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_Panel_Output.createSequentialGroup()
					.addGroup(gl_Panel_Output.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_Panel_Output.createSequentialGroup()
							.addGap(300)
							.addComponent(lblNewLabel_1))
						.addGroup(gl_Panel_Output.createSequentialGroup()
							.addGap(27)
							.addComponent(lblResult))
						.addGroup(gl_Panel_Output.createSequentialGroup()
							.addGap(19)
							.addComponent(scrollPane_OutputSelect, GroupLayout.DEFAULT_SIZE, 542, Short.MAX_VALUE)))
					.addGap(22))
		);
		gl_Panel_Output.setVerticalGroup(
			gl_Panel_Output.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_Panel_Output.createSequentialGroup()
					.addGap(5)
					.addComponent(lblNewLabel_1)
					.addGap(11)
					.addComponent(lblResult)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(scrollPane_OutputSelect, GroupLayout.DEFAULT_SIZE, 35, Short.MAX_VALUE)
					.addGap(13))
		);
		
		tableOutputOfSelect = new JTable();
		tableOutputOfSelect.setModel(new DefaultTableModel(
			new Object[][] {
				{null, null},
				{null, null},
			},
			new String[] {
				"b", "a"
			}
		));
		tableOutputOfSelect.setSize(new Dimension(0, 20));
		scrollPane_OutputSelect.setViewportView(tableOutputOfSelect);
		Panel_Output.setLayout(gl_Panel_Output);
		
				textAreaQuery = new JTextArea();
				scrollPane_3.setViewportView(textAreaQuery);
				textAreaQuery.setWrapStyleWord(true);
				textAreaQuery.setLineWrap(true);
				textAreaQuery.setVisible(false);
		panel_Query.setLayout(gl_panel_Query);

		panel_TableContent = new JPanel();
		panel_TableContent.setVisible(false);
		
				panel_NewTable = new JPanel();
				panel_NewTable.setBackground(Color.WHITE);
				panel_NewTable.setBorder(new LineBorder(new Color(192, 192, 192), 1,
						true));
				tabbedPane.addTab("New Table", null, panel_NewTable, null);
				
						JScrollPane scrollPane = new JScrollPane();
						scrollPane.setForeground(Color.WHITE);
						scrollPane.setBackground(Color.WHITE);
						btnCreateTable = new JButton("Create");
						btnCreateTable.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent arg0) {
								createNewTable();
							}
						});
						
								JButton btnAddNewCol = new JButton("");
								btnAddNewCol.addMouseListener(new MouseAdapter() {
									@Override
									public void mouseClicked(MouseEvent arg0) {
										btnAddNewCol_Clicked(arg0);
									}
								});
								btnAddNewCol.setIcon(new ImageIcon(MainScreen.class
										.getResource("/resource/add-icon.png")));
								
								btnDeleteCol = new JButton("");
								btnDeleteCol.addMouseListener(new MouseAdapter() {
									@Override
									public void mouseClicked(MouseEvent arg0) {
										btnDeleteCol_Clicked(arg0);	
									}
								});
								btnDeleteCol.setIcon(new ImageIcon(MainScreen.class.getResource("/resource/Subtract-icon.png")));
								
								btnResetTable = new JButton("");
								btnResetTable.addMouseListener(new MouseAdapter() {
									@Override
									public void mouseClicked(MouseEvent arg0) {
										btnResetTable_Clicked(arg0);
									}
								});
								btnResetTable.setIcon(new ImageIcon(MainScreen.class.getResource("/resource/Actions-edit-clear-icon.png")));
								
								btnSaveTable = new JButton("Save");
								btnSaveTable.setVisible(false);
								
								btnCancelEdit = new JButton("Cancel");
								btnCancelEdit.setVisible(false);
								btnCancelEdit.addMouseListener(new MouseAdapter() {
									@Override
									public void mouseClicked(MouseEvent arg0) {
										btnCancelEdit_Clicked(arg0);
									}
								});
								GroupLayout gl_panel_NewTable = new GroupLayout(panel_NewTable);
								gl_panel_NewTable.setHorizontalGroup(
									gl_panel_NewTable.createParallelGroup(Alignment.TRAILING)
										.addGroup(gl_panel_NewTable.createSequentialGroup()
											.addGap(10)
											.addGroup(gl_panel_NewTable.createParallelGroup(Alignment.TRAILING)
												.addGroup(gl_panel_NewTable.createSequentialGroup()
													.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 478, Short.MAX_VALUE)
													.addGap(18)
													.addGroup(gl_panel_NewTable.createParallelGroup(Alignment.LEADING)
														.addComponent(btnAddNewCol, GroupLayout.PREFERRED_SIZE, 37, GroupLayout.PREFERRED_SIZE)
														.addComponent(btnDeleteCol, GroupLayout.PREFERRED_SIZE, 37, GroupLayout.PREFERRED_SIZE)
														.addComponent(btnResetTable, GroupLayout.PREFERRED_SIZE, 37, GroupLayout.PREFERRED_SIZE))
													.addGap(52))
												.addGroup(gl_panel_NewTable.createSequentialGroup()
													.addComponent(btnSaveTable, GroupLayout.PREFERRED_SIZE, 65, GroupLayout.PREFERRED_SIZE)
													.addPreferredGap(ComponentPlacement.RELATED)
													.addComponent(btnCancelEdit, GroupLayout.PREFERRED_SIZE, 65, GroupLayout.PREFERRED_SIZE)
													.addPreferredGap(ComponentPlacement.RELATED)
													.addComponent(btnCreateTable)
													.addGap(118))))
								);
								gl_panel_NewTable.setVerticalGroup(
									gl_panel_NewTable.createParallelGroup(Alignment.LEADING)
										.addGroup(gl_panel_NewTable.createSequentialGroup()
											.addGap(24)
											.addGroup(gl_panel_NewTable.createParallelGroup(Alignment.LEADING)
												.addGroup(gl_panel_NewTable.createSequentialGroup()
													.addComponent(btnAddNewCol)
													.addPreferredGap(ComponentPlacement.UNRELATED)
													.addComponent(btnDeleteCol, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
													.addPreferredGap(ComponentPlacement.UNRELATED)
													.addComponent(btnResetTable, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
													.addContainerGap())
												.addGroup(gl_panel_NewTable.createSequentialGroup()
													.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 255, Short.MAX_VALUE)
													.addPreferredGap(ComponentPlacement.RELATED)
													.addGroup(gl_panel_NewTable.createParallelGroup(Alignment.BASELINE)
														.addComponent(btnCreateTable)
														.addComponent(btnCancelEdit)
														.addComponent(btnSaveTable))
													.addGap(36))))
								);
								
										tableNewTable = new JTable(myNewTableModel);
										tableNewTable.getModel().addTableModelListener(myNewTableModel);
										tableNewTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
										scrollPane.setViewportView(tableNewTable);
										tableNewTable.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
										panel_NewTable.setLayout(gl_panel_NewTable);
		panel_TableContent.setBackground(Color.WHITE);
		tabbedPane.addTab("Table Content", null, panel_TableContent, null);

		JScrollPane scrollPane_1 = new JScrollPane();
		
		btnAddNewRecord = new JButton("");
		btnAddNewRecord.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				btnAddNewRecord_Clicked();
			}
		});
		btnAddNewRecord.setIcon(new ImageIcon(MainScreen.class.getResource("/resource/add-icon.png")));
		
		btnDeleteRecord = new JButton("");
		btnDeleteRecord.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				btnDeleteRecord_Clicked();
			}
		});
		btnDeleteRecord.setIcon(new ImageIcon(MainScreen.class.getResource("/resource/Subtract-icon.png")));
		GroupLayout gl_panel_TableContent = new GroupLayout(panel_TableContent);
		gl_panel_TableContent.setHorizontalGroup(
			gl_panel_TableContent.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_TableContent.createSequentialGroup()
					.addGap(22)
					.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 505, Short.MAX_VALUE)
					.addGap(18)
					.addGroup(gl_panel_TableContent.createParallelGroup(Alignment.LEADING)
						.addComponent(btnAddNewRecord, GroupLayout.PREFERRED_SIZE, 37, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnDeleteRecord, GroupLayout.PREFERRED_SIZE, 37, GroupLayout.PREFERRED_SIZE))
					.addGap(15))
		);
		gl_panel_TableContent.setVerticalGroup(
			gl_panel_TableContent.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_TableContent.createSequentialGroup()
					.addGap(21)
					.addGroup(gl_panel_TableContent.createParallelGroup(Alignment.LEADING)
						.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 313, Short.MAX_VALUE)
						.addGroup(gl_panel_TableContent.createSequentialGroup()
							.addComponent(btnAddNewRecord, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
							.addGap(11)
							.addComponent(btnDeleteRecord, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)))
					.addGap(58))
		);

		tableContent = new JTable();
		tableContent.addInputMethodListener(new InputMethodListener() {
			public void caretPositionChanged(InputMethodEvent arg0) {
			}
			public void inputMethodTextChanged(InputMethodEvent arg0) {
			}
		});
		scrollPane_1.setViewportView(tableContent);
		tableContent.setModel(new DefaultTableModel(new Object[][] {
				{ null, null }, { null, null }, }, new String[] {
				"New column02", "New column" }));
		panel_TableContent.setLayout(gl_panel_TableContent);
		tableContent.getModel().addTableModelListener(new TableModelListener() {

			@Override
			public void tableChanged(TableModelEvent arg0) {
				// TODO Auto-generated method stub
				tableContentChanged(arg0);
			}
		});
		JScrollPane scrollPane_2 = new JScrollPane();
		GroupLayout gl_Panel_Left = new GroupLayout(Panel_Left);
		gl_Panel_Left.setHorizontalGroup(gl_Panel_Left.createParallelGroup(
				Alignment.LEADING).addGroup(
				gl_Panel_Left.createSequentialGroup().addContainerGap()
						.addComponent(scrollPane_2).addContainerGap()));
		gl_Panel_Left.setVerticalGroup(gl_Panel_Left.createParallelGroup(
				Alignment.LEADING).addGroup(
				gl_Panel_Left
						.createSequentialGroup()
						.addGap(14)
						.addComponent(scrollPane_2, GroupLayout.DEFAULT_SIZE,
								345, Short.MAX_VALUE).addContainerGap()));

		treeTable = new JTree(myTreeModel);		
		treeTable.addTreeSelectionListener(new TreeSelectionListener() {
			public void valueChanged(TreeSelectionEvent arg0) {
				chooseTableFromTree(arg0);
			}
		});
		
		treeTable.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				treeTable_Clicked(arg0);
				
			}
		});		
		scrollPane_2.setViewportView(treeTable);
		treeTable.setMinimumSize(new Dimension(70, 0));
		
		popupMenu = new JPopupMenu();
		addPopup(treeTable, popupMenu);
		
		mntmEditTable = new JMenuItem("Edit Table");		
		mntmEditTable.setIcon(new ImageIcon(MainScreen.class.getResource("/resource/Text-Edit-icon.png")));
		mntmEditTable.addActionListener(ProcessPopupMenu_click);
		popupMenu.add(mntmEditTable);
		mntmOpenTable = new JMenuItem("Open Table");
		mntmOpenTable.setIcon(new ImageIcon(MainScreen.class.getResource("/resource/Folder-Open-icon.png")));
		mntmOpenTable.addActionListener(ProcessPopupMenu_click);
		popupMenu.add(mntmOpenTable);
		
		mntmCreateNewTable = new JMenuItem("Create New Table");
		mntmCreateNewTable.setIcon(new ImageIcon(MainScreen.class.getResource("/resource/Folder-New-Folder-icon.png")));
		mntmCreateNewTable.addActionListener(ProcessPopupMenu_click);
		popupMenu.add(mntmCreateNewTable);
		
		mntmDeleteTable = new JMenuItem("Delete Table");
		mntmDeleteTable.setIcon(new ImageIcon(MainScreen.class.getResource("/resource/Close-2-icon.png")));
		mntmDeleteTable.addActionListener(ProcessPopupMenu_click);
		popupMenu.add(mntmDeleteTable);
		Panel_Left.setLayout(gl_Panel_Left);
		contentPane.setLayout(gl_contentPane);
		myPostInit();
		tableModelContent = new DefaultTableModel();
		tableModelContent.addTableModelListener(new TableModelListener() {
			
			@Override
			public void tableChanged(TableModelEvent e) {
				// TODO Auto-generated method stub
				tableChange(e);
			}
		});
	}

	protected void mntmConfigConnection_actionPerformed() {
		// TODO Auto-generated method stub
		ConfigConnectionDialog configConnectionDialog=new ConfigConnectionDialog(this);
		int x=(this.getWidth()-configConnectionDialog.getWidth())/2+this.getX();
		int y=(this.getHeight()-configConnectionDialog.getHeight())/2+this.getY();
		configConnectionDialog.setLocation(x, y);
		configConnectionDialog.show();
		
	}

	protected void btnDeleteRecord_Clicked() {
		// TODO Auto-generated method stub
		int index=this.tableContent.getSelectedRow();
		if(index != -1)
		{
			try{
				deleteRow(index);
			}
			catch (Exception e) {
				// TODO: handle exception
				JOptionPane.showMessageDialog(this, "Delete row fail\n" + e.getMessage());
				return;
			}
			this.tableModelContent.removeRow(index);
			this.tableModelContent.fireTableRowsDeleted(0, 0);
		}
		
	}

	private void deleteRow(int index) throws Exception {
		// TODO Auto-generated method stub
		int nCols = tableModelContent.getColumnCount();
		RecordDAO recordDAO = new RecordDAO(_DATABASE_PATH);
		RecordDTO newRecord = new RecordDTO();
		newRecord.set_nCol(nCols);
		String[] recordData = new String[nCols];
		for(int i=0; i<nCols; i++)
		{
			recordData[i] = (String)tableModelContent.getValueAt(index, i);
		}
		newRecord.set_data(recordData);
		recordDAO.deleteRecord(selectedTreeNode.toString(), newRecord);
	}

	protected void btnAddNewRecord_Clicked() {
		if(newRow != -1)
		{
			try {
				addLastRow();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				JOptionPane.showMessageDialog(this, "Insert new row fail!\n" + e.getMessage());
				return;
			}
		}
		addNewRecordToTableContent();
	}

	/**
	 * 
	 */
	private void addNewRecordToTableContent() {
		newRow = tableModelContent.getRowCount();
		this.tableModelContent.addRow(tempRecord.get_data());
		this.tableModelContent.fireTableRowsInserted(0, 0);
	}

	private void addLastRow() throws Exception {
		// TODO Auto-generated method stub
		int nCols = tableModelContent.getColumnCount();
		RecordDAO recordDAO = new RecordDAO(_DATABASE_PATH);
		RecordDTO newRecord = new RecordDTO();
		newRecord.set_nCol(nCols);
		String[] recordData = new String[nCols];
		for(int i=0; i<nCols; i++)
		{
			recordData[i] = (String)tableModelContent.getValueAt(newRow, i);
		}
		newRecord.set_data(recordData);
		recordDAO.insertRecord(selectedTreeNode.toString(), newRecord);
		
	}

	protected void treeTable_Clicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		if(arg0.getButton()==MouseEvent.BUTTON3)
		{	
	
		}
		
	}

	protected void btnCancelEdit_Clicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		this.myNewTableModel.ResetTable();
		this.myNewTableModel.fireTableRowsInserted(0, 0);
		showTabNewTableInEditMode(false);
	}

	protected void btnResetTable_Clicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		ResetNewTable();
	}
	public void ResetNewTable()
	{
		this.myNewTableModel.ResetTable();
		this.myNewTableModel.fireTableRowsInserted(0, 0);
	}
	protected void btnDeleteCol_Clicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		int index=this.tableNewTable.getSelectedRow();
		if(-1!=index)
		{
			this.myNewTableModel.DeleteNewCol(index);
			this.myNewTableModel.fireTableRowsInserted(0, 0);
		}				
	}

	private Object selectedTreeNode = null;

	private void chooseTableFromTree(TreeSelectionEvent arg0) {
		TreePath tp = arg0.getNewLeadSelectionPath();
		if (null == tp)
			return;
		if(null == tp.getParentPath())
			return;
		selectedTreeNode = tp.getLastPathComponent();
		if (null == selectedTreeNode)
			return;
		
		if (1 == selectedTab)
		{			
			updateNewTableStructure();
			showTabNewTableInEditMode(true);
		
		}
		if (2 == selectedTab)
		{
			updateTableContent();
			newRow = -1;
		}
		 
	}
	
	private void updateTableContent() {
		if (selectedTreeNode != null) {
			TableDAO tbDAO = new TableDAO(_DATABASE_PATH);
			TableDTO tbDTO = null;
			try {
				tbDTO = tbDAO.getTable(selectedTreeNode.toString());
				if (null == tbDTO)
					return;
			} catch (Exception e) {
				// TODO: handle exception
				JOptionPane.showMessageDialog(this, e.getMessage());
			}
			tableModelContent = new DefaultTableModel();
			tableModelContent.addTableModelListener(new TableModelListener() {
				
				@Override
				public void tableChanged(TableModelEvent e) {
					// TODO Auto-generated method stub
					tableChange(e);
				}
			});
			Vector<ColInfoDTO> colInfos = tbDTO.get_colInfoList();
			int nCol=colInfos.size();
			for (int i = 0; i < nCol; i++) {
				tableModelContent
						.addColumn(colInfos.elementAt(i).get_colName());
			}
			
			Vector<RecordDTO> recordDTOs = tbDTO.get_recordList();
			tempRecord=new RecordDTO(nCol,new String[nCol]);			
			
			for (int i = 0; i < recordDTOs.size(); i++) {
				RecordDTO row = recordDTOs.elementAt(i);
				tableModelContent.addRow(row.get_data());
				
			}
			tableContent.setModel(tableModelContent);
		}
	}
	
	private RecordDTO tempRecord;

	private void tableContentChanged(TableModelEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println(arg0.getColumn());
		System.out.println(arg0.getFirstRow());
		System.out.println(((DefaultTableModel)arg0.getSource()).getValueAt(arg0.getFirstRow(), arg0.getColumn()));
		
	}

	/**
	 * 
	 */
	private void updateNewTableStructure() {
		TableDAO tbDAO = new TableDAO(_DATABASE_PATH);
		TableDTO tbDTO = null;
		try {
			tbDTO = tbDAO.getTable(selectedTreeNode.toString());
			if (null == tbDTO)
				return;
		} catch (Exception e) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(this, e.getMessage());
		}
		Vector<ColInfoDTO> colInfos = tbDTO.get_colInfoList();
		this.myNewTableModel.ResetTable();
		for (int i = 0; i < colInfos.size(); i++) {
			NewColInfo colInfo = new NewColInfo(colInfos.elementAt(i)
					.get_colName(), colInfos.elementAt(i).get_dataType(),
					colInfos.elementAt(i).get_constraint().get_isNotNull(),colInfos.elementAt(i).get_constraint().get_isPrimaryKey());
			myNewTableModel.AddNewCol(colInfo);
		}
		this.myNewTableModel.fireTableRowsInserted(0, 0);
	}

	private void createNewTable() {
		// TODO Auto-generated method stub
		String newTableName = JOptionPane.showInputDialog("Enter table name: ");
		if (null == newTableName) {
			JOptionPane.showMessageDialog(this, "Table name must be not null");
			return;
		}
		TableDTO tbDTO = new TableDTO();
		tbDTO.set_name(newTableName);
		Vector<ColInfoDTO> colInfos = new Vector<ColInfoDTO>();
		for (int i = 0; i < myNewTableModel.getRowCount(); i++) {
			ColInfoDTO colInfo = new ColInfoDTO();
			colInfo.set_colName((String) myNewTableModel.getValueAt(i, 0));
			colInfo.set_dataType((String) myNewTableModel.getValueAt(i, 1));
			ConstraintDTO constraint = new ConstraintDTO();
			Boolean notNull = (Boolean) myNewTableModel.getValueAt(i, 2);
			constraint.set_isNotNull(notNull);
			constraint.set_isPrimaryKey((Boolean)myNewTableModel.getValueAt(i, 3));
			colInfo.set_constraint(constraint);
			colInfos.add(colInfo);
		}
		tbDTO.set_colInfoList(colInfos);
		TableDAO tbDAO = new TableDAO(_DATABASE_PATH);
		try {
			tbDAO.addTable(tbDTO);
		} catch (Exception e) {
			// TODO: handle exception
			JOptionPane.showMessageDialog(this, e.getMessage());
		}
		updateTreeAndTableStructure();
		treeTable.setModel(myTreeModel);
		
	}

	private void excuteQuery() {
		// TODO Auto-generated method stub		
		String[] sqlStrs = textAreaQuery.getText().split("\n"); 
		for(int i=0; i<sqlStrs.length; i++)
		{
			QueryProccessor queryProcessor = new QueryProccessor(sqlStrs[i]);
			try {
				Object result=queryProcessor.excuteQuey();
				System.out.println("output of select");
				if(null==result)
				{
					System.out.println("output: null");
					this.scrollPane_OutputSelect.setVisible(false);
				}
				else
				{	
					System.out.println("output: ok");					
					UpdateOutputTable((TableDTO)result);
					this.scrollPane_OutputSelect.setVisible(true);
				}
			} catch (Exception e) {
				// TODO: handle exception
				this.lblResult.setText("Message: "+ "Succeed " + (i) + " statements\n Error at statement " + (i + 1) + " : " + e.getMessage());
				this.scrollPane_OutputSelect.setVisible(false);
				//JOptionPane.showMessageDialog(this, "Succeed " + (i) + " statements\n Error at statement " + (i + 1) + " : " + e.getMessage());
				return;
			}
		}
		this.lblResult.setText("Message: "+ "Successfully !");		
	}

	private void btnQuery_Click(MouseEvent arg0) {		
		if (isShowIconDatabase) {
			ShowQueryScreen(true);
		} else {
			ShowQueryScreen(false);
		}
	}
	
	public void ShowQueryScreen(boolean ishow)
	{
		this.tabbedPane.setSelectedIndex(0);
		this.lblIconDatabase.setVisible(!ishow);
		this.scrollPane_3.setVisible(ishow);
		btnExecute.setVisible(ishow);
		Panel_Output.setVisible(ishow);
		textAreaQuery.setVisible(ishow);
		isShowIconDatabase = !ishow;
	}

	// Them mot cot moi cho table.
	public void btnAddNewCol_Clicked(MouseEvent e) {
		NewColInfo colInfo = new NewColInfo("new col", "String", false,false);
		this.myNewTableModel.AddNewCol(colInfo);
		this.myNewTableModel.fireTableRowsInserted(0, 0);
	}

	public void myPreInit() {
		myNewTableModel = new MyNewTableModel();
		root=new DefaultMutableTreeNode("Tables");
		myTreeModel=new MyTreeModel(root);
		updateTreeAndTableStructure();
	}
	
	private void updateTreeAndTableStructure() {
		File DbFile = new File(_DATABASE_PATH);
		treeNode = new DefaultMutableTreeNode("Tables");
		if (!DbFile.exists()) {
			try {
				DbFile.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			myTreeModel = new MyTreeModel(treeNode);
			return;
		}
		TableDAO tbDAO = new TableDAO(_DATABASE_PATH);
		Vector<TableDTO> tableList = null;
				
		try {
			tableList = tbDAO.getAllTable();
		} catch (Exception e) {
			return;
		}
		if (null == tableList) {
			myTreeModel = new MyTreeModel(treeNode);
			return;
		}
		for (int i = 0; i < tableList.size(); i++)
			treeNode.add(new DefaultMutableTreeNode(tableList.elementAt(i)
					.get_name()));
		myTreeModel = new MyTreeModel(treeNode);
	}

	public void myPostInit() {
		
		String[] DataType = new String[] {"float", "String" };
		JComboBox combobox = new JComboBox(DataType);
		TableColumn col = tableNewTable.getColumnModel().getColumn(1);
		col.setCellEditor(new DefaultCellEditor(combobox));
		col.setCellRenderer(new MyComboBoxRenderer(DataType));
		JCheckBox checkBox = new JCheckBox();
		TableColumn col1 = tableNewTable.getColumnModel().getColumn(2);
		col1.setCellEditor(new DefaultCellEditor(checkBox));
		col1.setCellRenderer(new MyCheckBoxRenderer(true));
		
		JCheckBox checkBox1 = new JCheckBox();
		TableColumn col2 = tableNewTable.getColumnModel().getColumn(3);
		col2.setCellEditor(new DefaultCellEditor(checkBox1));
		col2.setCellRenderer(new MyCheckBoxRenderer(true));
	}
	
	public void btnCreate_Click(MouseEvent arg0) {
		this.tabbedPane.setSelectedIndex(1);
		this.myNewTableModel.ResetTable();
		this.myNewTableModel.fireTableRowsDeleted(0,0);
		this.showTabNewTableInEditMode(false);
	}

	/**
	 * @param arg0
	 */
	private int selectedTab = 0;
	private JButton btnDeleteCol;
	private JButton btnResetTable;
	private JScrollPane scrollPane_3;
	private JPanel panel_TableContent;
	private JButton btnSaveTable;
	private JButton btnCancelEdit;
	private JTable tableOutputOfSelect;
	private JLabel lblResult;
	private JPopupMenu popupMenu;
	private JMenuItem mntmEditTable;
	private JMenuItem mntmOpenTable;

	private void tabChanged(ChangeEvent arg0) {
		JTabbedPane pane = (JTabbedPane) arg0.getSource();
		selectedTab = pane.getSelectedIndex();
		if(2 == selectedTab)
		{
			updateTableContent();
			newRow = -1;
		}
	}

	public class MyComboBoxEditor extends DefaultCellEditor {
		public MyComboBoxEditor(String[] items) {
			super(new JComboBox(items));
		}
	}

	public class MyCheckboxEditor extends DefaultCellEditor {
		public MyCheckboxEditor(boolean value) {
			super(new JCheckBox("", value));
		}
	}

	public class MyComboBoxRenderer extends JComboBox implements
			TableCellRenderer {
		public MyComboBoxRenderer(String[] items) {
			super(items);
		}

		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			if (isSelected) {
				setForeground(table.getSelectionForeground());
				super.setBackground(table.getSelectionBackground());
			} else {
				setForeground(table.getForeground());
				setBackground(table.getBackground());
			}
			setSelectedItem(value);
			return this;
		}
	}

	public class MyCheckBoxRenderer extends JCheckBox implements
			TableCellRenderer {
		public MyCheckBoxRenderer(boolean value) {
			super("", value);
		}

		@Override
		public Component getTableCellRendererComponent(JTable table,
				Object value, boolean isSelected, boolean hasFocus, int row,
				int column) {
			if (value.toString().equalsIgnoreCase("true")) {
				this.setSelected(true);
			} else
				this.setSelected(false);
			return this;
		}

	}

	// Class data cua tree.
	class MyTreeModel extends DefaultTreeModel implements TreeSelectionListener {
		private DefaultMutableTreeNode root;
		private String rootName = "Tables";
		private Vector<String> listTableName;

		public MyTreeModel(TreeNode root) {
			super(root);
			DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) root;			
			rootName = (String) parentNode.getUserObject();
		}

		public Object getChild(Object parent, int index) {
			DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) parent;
			String parentName = (String) parentNode.getUserObject();

			if (parentName.equals(rootName))
				return super.getChild(parent, index);
			else
				return listTableName.elementAt(index);
		}

		@Override
		public void valueChanged(TreeSelectionEvent e) {
			
		}
	}

	// Class data cua panel newtable
	class MyNewTableModel extends AbstractTableModel implements
			TableModelListener {
		private Vector<NewColInfo> ColInfos;
		public MyNewTableModel() {
			ColInfos = new Vector<NewColInfo>();
		}

		public void ResetTable() {
			// TODO Auto-generated method stub
			ColInfos.removeAllElements();
		}

		public void AddNewCol(NewColInfo colInfo) {
			ColInfos.add(colInfo);
		}
		public void DeleteNewCol(int index)
		{
			ColInfos.remove(index);
		}
		
		private String[] columnNames = { "Column Name", "DataType", "Not null","Primary key" };

		@Override
		public int getColumnCount() {
			return columnNames.length;
		}

		@Override
		public int getRowCount() {
			return ColInfos.size();
		}

		@Override
		public String getColumnName(int arg0) {
			return columnNames[arg0];
		}

		@Override
		public Object getValueAt(int row, int col) {
			NewColInfo colInfo = ColInfos.elementAt(row);
			switch (col) {
			case 0:
				return colInfo.getColName();
			case 1:
				return colInfo.getDataType();
			case 2:
				return colInfo.isNull();
			case 3:
			{
				return colInfo.isPrimeryKey();				
			}
			default:
				break;
			}
			return null;
		}

		@Override
		public void setValueAt(Object Value, int rowIndex, int columnIndex) {
			switch (columnIndex) {
			case 0: {
				ColInfos.elementAt(rowIndex).setColName((String) Value);
				break;
			}
			case 1: {
				ColInfos.elementAt(rowIndex).setDataType((String) Value);
				break;
			}
			case 2: {
				if (Value.toString().equalsIgnoreCase("true"))
					ColInfos.elementAt(rowIndex).setNull(true);
				else
					ColInfos.elementAt(rowIndex).setNull(false);
				break;
			}
			case 3:
			{
				if (Value.toString().equalsIgnoreCase("true"))
					ColInfos.elementAt(rowIndex).setPrimeryKey(true);
				else
					ColInfos.elementAt(rowIndex).setPrimeryKey(false);
				break;
			}
			default:
				break;
			}
		}

		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			return true;
		}
		
		@Override
		public void tableChanged(TableModelEvent e) {
		}

	}
	
	public void showTabNewTableInEditMode(boolean isEditMode)
	{
		if(isEditMode)
		{
			this.btnSaveTable.setVisible(true);
			this.btnCancelEdit.setVisible(true);
			this.btnCreateTable.setVisible(false);
			
		}
		else
		{
			this.btnSaveTable.setVisible(false);
			this.btnCancelEdit.setVisible(false);
			this.btnCreateTable.setVisible(true);
		}
	}
	
	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}		
			
			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}
	
	private ActionListener ProcessPopupMenu_click=new ActionListener() {		
		@Override
		public void actionPerformed(ActionEvent e) {
			popupMenu_Click(e);
		}
	};
	private JMenuItem mntmCreateNewTable;
	private JMenuItem mntmDeleteTable;
	private JScrollPane scrollPane_OutputSelect;
	private JButton btnAddNewRecord;
	private JButton btnDeleteRecord;
	private DefaultTableModel tableModelContent;
	private boolean allowUpdateRow = true;
	public void UpdateOutputTable(TableDTO tableDTO)	
	{		
		Vector<RecordDTO> recordList=tableDTO.get_recordList();
		Vector<ColInfoDTO> colList=tableDTO.get_colInfoList();
		int nCol=colList.size();
		int nRecord=recordList.size();
		
		String[] Cols=new String[nCol];
		String[][] Records=new String[nRecord][nCol];
		
		for(int i=0;i<nCol;i++)
		{
			Cols[i]=colList.get(i).get_colName();
		}
		
		for(int i=0;i<nRecord;i++)
		{
			for(int j=0;j<nCol;j++)
			{
				Records[i][j]=recordList.get(i).get_data(j);
			}
		}		
				
		tableOutputOfSelect.setModel(new DefaultTableModel(
				Records,Cols
			));
		
		
	}

	/**
	 * @param e
	 */
	private void tableChange(TableModelEvent e) {
		int col = e.getColumn();
		int row = e.getLastRow();
		if(col == tableModelContent.getColumnCount()-1 
				&& row == tableModelContent.getRowCount()-1)
		{
			if(newRow != -1)
			{
				try {
					addLastRow();
					addNewRecordToTableContent();
				} catch (Exception ex) {
					// TODO Auto-generated catch block
					JOptionPane.showMessageDialog(this, "Insert new row fail!\n" + ex.getMessage());
					updateTableContent();
					return;
				}
			}
		}
		if(col != -1 && newRow == -1)
		{
			RecordDAO recordDAO = new RecordDAO(_DATABASE_PATH);
			RecordDTO newRecord = new RecordDTO();
			int nCols = tableModelContent.getColumnCount();
			newRecord.set_nCol(nCols);
			String[] recordData = new String[nCols];
			for(int i=0; i<nCols; i++)
			{
				recordData[i] = (String)tableModelContent.getValueAt(row, i);
			}
			newRecord.set_data(recordData);
			RecordDTO oldRecord = new RecordDTO();
			try {
				oldRecord = recordDAO.getAllRecord(selectedTreeNode.toString()).elementAt(row);
				recordDAO.updateRecord(selectedTreeNode.toString(), oldRecord, newRecord);
			} catch (Exception ex) {
				// TODO Auto-generated catch block
				JOptionPane.showMessageDialog(this, "Update row fail\n" + ex.getMessage());
			}
			updateTableContent();
		}
	}

	/**
	 * @param e
	 */
	private void popupMenu_Click(ActionEvent e) {
		String command=e.getActionCommand();
		if(command.equalsIgnoreCase("Edit Table"))
		{
			tabbedPane.setSelectedIndex(1);
			updateNewTableStructure();
			showTabNewTableInEditMode(true);				
		}
		else if(command.equalsIgnoreCase("Open Table"))
		{
			tabbedPane.setSelectedIndex(2);
			updateTableContent();
		}
		else if(command.equalsIgnoreCase("Create New Table"))
		{
			ResetNewTable();
			tabbedPane.setSelectedIndex(1);
			showTabNewTableInEditMode(false);

		}	
		else if(command.equalsIgnoreCase("Delete Table"))
		{
			TableDAO tbDAO  = new TableDAO(_DATABASE_PATH);
			try{
				tbDAO.removeTable(selectedTreeNode.toString());
			}catch (Exception ex) {
				JOptionPane.showMessageDialog(this, "Delete table fail!\n" + ex.getMessage());
				return;
			}
			updateTreeAndTableStructure();
			treeTable.setModel(myTreeModel);
		}
	}
	
	public void setPortAtServer(int port){
		
		Server.PORT_SERVER = port;
		server = new Server();
		server.AllowConnect();
		
	}
}
